/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.atomojo.sparql;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.TreeMap;

/**
 *
 * @author alex
 */
public class Prologue {

   URI base;
   Map<String,URI> prefixes;
   public Prologue() {
      this.base = null;
      this.prefixes = new TreeMap<String,URI>();
      this.prefixes.put("rdf", URI.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
   }

   public URI getBase() {
      return base;
   }

   public void setBase(URI base) {
      this.base = base;
   }
   
   public Map<String,URI> getPrefixes() {
      return prefixes;
   }
   
   public URI getNamespace(String prefix) {
      return this.prefixes.get(prefix);
   }
   
   public URI resolve(String href)
      throws URISyntaxException
   {
      return base==null ? new URI(href) : base.resolve(href);
   }
   
   public URI expand(String qname)
      throws URISyntaxException
   {
      int colon = qname.indexOf(':');
      String prefix = qname.substring(0,colon);
      URI uri = prefixes.get(prefix);
      if (uri==null) {
         return null;
      }
      return new URI(uri.toString()+qname.substring(colon+1));
   }
   
   public String toString() {
      StringBuilder builder = new StringBuilder();
      if (base!=null) {
         builder.append("BASE <");
         builder.append(base.toString());
         builder.append(">\n");
      }
      for (String prefix : prefixes.keySet()) {
         if (prefix.equals("rdf")) {
            continue;
         }
         builder.append("PREFIX ");
         builder.append(prefix);
         builder.append(": <");
         builder.append(prefixes.get(prefix).toString());
         builder.append(">\n");
      }
      return builder.toString();
   }
}
